import UIKit

class ConversationItem {
    
    var chat: OCTChat?

    var conversationId: String = ""
    var ownerId: String = ""
    var category: String? = nil
    var name: String = ""
    var iconUrl: String = ""
    var announcement: String = ""
    var lastReadMessageId: String? = nil
    var unseenMessageCount: Int = 0
    var status: Int = ConversationStatus.START.rawValue
    var muteUntil: String? = nil
    var codeUrl: String? = nil
    var pinTime: String? = nil
    var createdAt: String = ""

    var ownerIdentityNumber: String = ""
    var ownerFullName: String = ""
    var ownerAvatar: Data?
    var ownerAvatarUrl: String = ""
    var ownerIsVerified = false

    var messageStatus: String = ""
    var messageId: String = ""
    var content: String = ""
    var contentType: String = ""

    var senderId: String = ""
    var senderFullName: String = ""

    var participantFullName: String? = nil
    var participantUserId: String? = nil

    var appId: String? = nil
    var actionName: String? = nil

    var ownerIsBot: Bool {
        return !(appId?.isEmpty ?? true)
    }

    var isMuted: Bool {
        guard let muteUntil = self.muteUntil else {
            return false
        }
        return muteUntil > Date().toUTCString()
    }
    
//    convenience init(ownerUser: UserItem) {
//        self.init()
//
//        name = ownerUser.fullName
//        iconUrl = ownerUser.avatarUrl
//        ownerId = ownerUser.userId
//        ownerIdentityNumber = ownerUser.identityNumber
//        category = ConversationCategory.CONTACT.rawValue
//        contentType = MessageCategory.SIGNAL_TEXT.rawValue
//    }
    
    func getConversationName() -> String {
        guard category == ConversationCategory.CONTACT.rawValue else {
            return name
        }
        return ownerFullName
    }

    func isGroup() -> Bool {
        return category == ConversationCategory.GROUP.rawValue
    }

    func isNeedCachedGroupIcon() -> Bool {
        return category == ConversationCategory.GROUP.rawValue && (iconUrl.isEmpty || !FileManager.default.fileExists(atPath: MixinFile.groupIconsUrl.appendingPathComponent(iconUrl).path))
    }
    
    static func create(by chat: OCTChat) -> ConversationItem {
        guard let friend = chat.friends.firstObject() as? OCTFriend else {
            return ConversationItem()
        }
        
        let model = ConversationItem()
        model.ownerFullName = friend.nickname
        model.ownerIdentityNumber = "\(friend.friendNumber)" //"\(userItem.fullName.hashValue % 24)"
        model.ownerAvatar = friend.avatarData
        model.category = ConversationCategory.CONTACT.rawValue
        if let lastMessage = chat.lastMessage() {
            model.content = lastMessage.0
            model.contentType = lastMessage.1
            model.messageStatus = lastMessage.2 ? MessageStatus.READ.rawValue : MessageStatus.UNKNOWN.rawValue
        }
        
        model.chat = chat
        return model
    }
}
